package com.hotcode;

/**
 * @Author: huangzhigao
 * @Date: 2023/2/25 17:30
 */
public class leecode79 {
    public boolean exist(char[][] board, String word) {
        int row = board.length;
        int column = board[0].length;
        boolean[][] visited = new boolean[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (check(board, visited, i, j, word, 0)) {
                    return true;
                }
            }
        }

        return true;
    }


    public boolean check(char[][] board, boolean[][] visited, int row, int column, String word, int k) {
        if (board[row][column] != word.charAt(k)) {
            return false;
        }
        if (word.length() - 1 == k) {
            return true;
        }
        visited[row][column] = true;
        boolean result = false;
        int[][] directions = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        for (int i = 0; i < directions.length; i++) {
            int newRow = directions[i][0] + row;
            int newCol = directions[i][1] + column;
            if (newRow >= 0 && newRow < board.length && newCol >= 0 && newCol < board[0].length) {
                if (!visited[newRow][newCol] && check(board, visited, newRow, newCol, word, k + 1)) {
                    result = true;
                    break;
                }
            }
        }


        visited[row][column] = false;
        return result;

    }
}
